<template>
    <!--添加新老师按钮，触发编辑同一个弹窗-->
    <div class="mb-4">
    <el-button type="primary"@click='centerDialogVisible=true,displayTeacherInformation(2),changeNumFun(2)' >添加老师</el-button>
    </div>
    <!--与修改老师用的同一个组件，但点击保存时候，editTeacher按键会根据changeNum的值来判断是添加还是修改-->


    <div>
        <el-table
        :data="displayedTableData"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        >
        <el-table-column prop="name" label="老师" sortable  width="180"/>
        <el-table-column prop="sex" label="性别" sortable width="210"/>
        <el-table-column prop="phone" label="手机号" sortable  width="230"/>
        <el-table-column prop="note" label="备注"  sortable width="380"/>
        <el-table-column prop="manipulation" label="操作" width="300">
        

        <!--按钮组件-->
        <template #default="{$index}">
            <el-button type="primary" @click="centerDialogVisible = true,giveID($index),displayTeacherInformation(1),changeNumFun(1)">编辑</el-button>
            <el-button type="success" @click="drawer = true,showDetailMessage($index),giveID($index)">查看</el-button>
            <el-button type="info" @click="deleteRow($index)">删除</el-button>
        </template>
        </el-table-column>
        </el-table>
    </div>

    <!--  -------跳窗窗口组件---------  -->

    <el-dialog v-model="centerDialogVisible" :title="title" width="700" center>
        
        <!--表单组件-->
        <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="老师姓名">
      <el-input v-model="form.name" placeholder="请输入老师姓名"  />
    </el-form-item>
    <el-form-item label="出生日期">
      <el-col :span="11">
        <el-date-picker
          v-model="form.birthday"
          type="date"
          placeholder="Pick a date"
          style="width: 100%"
        />
      </el-col>
    </el-form-item>
    <el-form-item label="性别">
      <el-radio-group v-model="form.sex">
        <el-radio value="男">男</el-radio>
        <el-radio value="女">女</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="老师电话">
      <el-input v-model="form.phone" placeholder="请输入电话"  />
    </el-form-item>

    <!--邮箱-->
    <el-form
    ref="formRef"
    style="max-width: 600px"
    :model="dynamicValidateForm"
    label-width="auto"
    class="demo-dynamic"
  >
    <el-form-item
      prop="email"
      label="Email"
    >
      <el-input v-model="form.roleEmail" />
    </el-form-item>
  </el-form>
    <!--邮箱-->


    <el-form-item label="老师简述">
      <el-input v-model="form.note" type="textarea" />
    </el-form-item>
    <el-form-item label="老师介绍">
      <el-input v-model="form.introduce" type="textarea" />
    </el-form-item>
    
  </el-form>
        <!--表单组件-->

        <template #footer>
        <div class="dialog-footer">
            <el-button @click="centerDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="centerDialogVisible = false,editTeacher(changeNum)">
            保存
            </el-button>
        </div>
        </template>
    </el-dialog>
    <!--####跳窗窗口组件#####-->


    <!--显示当前一共多少条数据-->
    <div>当前{{startlocation}}条到{{endlocation}}条，共{{total}}条</div>
    <!--显示当前一共多少条数据#-->

    <!--分页组件 el-pagination在点击换页后触发@current-change事件，传递参数val为当前页码-->
    <div class="example-pagination-block">
    <div class="example-demonstration"/>
    <el-pagination layout="prev, pager, next" :total="total" 
    :pageSize="pageSize"
    @current-change="handleCurrentChange"/>
    </div>
    <!--分页组件#-->

  
  <!--侧拉框Drawer-->
  <el-drawer v-model="drawer" title="老师详细信息" size="87%">
    <div>
      <!--框内内部描述列表组件-->
      <el-descriptions :title="teacherForm.name">
      <el-descriptions-item label="老师性别">{{teacherForm.sex}}</el-descriptions-item>
      <el-descriptions-item label="老师电话">{{teacherForm.phone}}</el-descriptions-item>
      <el-descriptions-item label="老师生日">{{teacherForm.birthday}}</el-descriptions-item>
      <el-descriptions-item label="老师邮箱">{{ teacherForm.roleEmail }}</el-descriptions-item>
      <el-descriptions-item label="Remarks">
        <el-tag size="small">{{ teacherForm.introduce }}</el-tag>
      </el-descriptions-item>
    </el-descriptions>
      <!--框内内部描述列表组件#-->


    <!--添加老师的上课记录以及老师评价-->
      <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="老师介绍" name="first">
          {{teacherForm.name}}是一个{{teacherForm.note}}的人,他/她和蔼可亲
        </el-tab-pane>
        <el-tab-pane label="上课记录" name="second">
          上课的记录（表格形式）
          <el-table :data="teacherForm.teacherVoList" style="width: 100%">
              <el-table-column prop="name" label="课程名" width="280" />
              <el-table-column prop="classDateTime" label="上课时间" width="300" />
              <el-table-column prop="students" label="会员名称" width="480"/>
              <el-table-column prop="timesCost" label="上课时间" width="280" />
          </el-table>
        </el-tab-pane>
        
    </el-tabs>
    <!--添加老师上课记录和评价#-->


      <!--更改按钮-->
      <el-button @click="centerDialogVisible = true,displayTeacherInformation(1)":changeNum=1>修改信息</el-button>
      <el-button @click="drawer = false">返回</el-button>
      
      <!--更改按钮#-->
      
    </div>


  </el-drawer>
  <!--侧拉框-->
    
</template>

   
<script lang="ts" setup>
    import { ref,reactive, onMounted} from 'vue'
    import axios from 'axios'
     //添加router
    import {useRouter} from 'vue-router'
    //tab标签页
    import { TabsPaneContext } from 'element-plus'
    //tab标签页#

    //引入teacher.js
    import {getlength,getOnePageDate,deleteTeacher,checkTeacher
      ,updateTeacher,addTeacher} from '@/api/teacher.js'

    //定义router变量
    const router  = useRouter()

    //侧拉框内部实验
    const activeName = ref('first')
    const handleClick = (tab: TabsPaneContext, event: Event) => {
      console.log(tab, event)
    }


    //侧拉框
    const drawer = ref(false)
    let teacherIndex=ref(0)
    //侧拉框#


    //表单
    const form = reactive({
        id: 8080,
        name: '',
        phone: '',
        birthday: '',
        sex: '',
        introduce:'',
        note:'',
        roleEmail:''
        })
    //表单#
    //老师的详细信息
    const teacherForm=reactive({
        id: 8080,
        name: '',
        phone: '',
        birthday: '',
        sex: '',
        introduce:'',
        note:'',
        roleEmail:'',
        teacherVoList:[]
        })

    //赋值id属性
    const giveID = (index) => {
        form.id = displayedTableData.value[index].id
    }

    //邮箱
    const formRef = ref()
    const dynamicValidateForm = reactive<{
      email: string
    }>
    ({
      email: '',
    })

    const changeNum=ref(0)
    //传入一个数字,更改changeNum的值的函数
    const changeNumFun=(num)=>{
      changeNum.value=num
    }

    //邮箱#
    //添加和修改老师弹窗的标题
    const title = ref('添加老师')
    const centerDialogVisible = ref(false)
    const pageSize = 10 // 每页显示的条目数量
    const currentPage = ref(1) // 当前页码
    const total = ref(0) // 总记录数
    const displayedTableData = ref([]) // 存储当前页面显示的数据
  
    //本页数据起始端和结束端
    let startlocation=(currentPage.value-1)*10
    let endlocation=0
    
    

    const displayTeacherInformation = (Numshow) => {
      if(Numshow==1){
        title.value="编辑信息"
      }else{
        title.value="添加老师"
      }
    }
    const editTeacher = (identifyNum) => {
      console.log("修改或者添加老师数据为:",form)
    
      //如果传入参数为2则执行添加操作
      if(identifyNum==2){
        title.value="添加老师"

        addTeacher(form).then(res => {
          if(res.data.code==200){
            console.log("===添加数据库数据===")
            console.log("res为:",res)
            displayedTableData.value = res.data.data
            displayCurrentPageData(); // 刷新数据
          }else{
            alert("手机号已经存在")
            console.log("===手机号已经存在===")
          }
          
        }).catch(err => {
            // error
            console.log("报了错误",err)
          })

      }else{
        title.value="修改老师"
        let TeacherID=form.id

        updateTeacher(form).then(res => {
          if(res.data.code==200){
            console.log("===更新数据库数据===")
            displayedTableData.value = res.data.data
            displayCurrentPageData(); // 刷新数据
          }else{
            alert("您正在修改为已存在的手机号")
            console.log("===手机号已经存在===")
          }
          
          }).catch(err => {
            // error
            console.log(err)
          })

        //如果是在侧拉框页面，需要更新侧拉框中的数据
        if(drawer.value==true){
          checkTeacher(TeacherID).then(res => {
            
            //将res.data赋值给teacherForm
            teacherForm.id=res.data.id
            teacherForm.name=res.data.data.name
            teacherForm.phone=res.data.data.phone
            teacherForm.birthday=res.data.data.birthday
            teacherForm.sex=res.data.data.sex
            teacherForm.introduce=res.data.data.introduce
            teacherForm.note=res.data.data.note
            teacherForm.roleEmail=res.data.data.roleEmail
            teacherForm.teacherVoList=res.data.data.teacherVoList
            console.log("刷新后的老师详情：",teacherForm)
          }).catch(err => {
            // error
            console.log(err)
          })
        }
        //侧拉框内内容更新
      }
    }

    const showDetailMessage=(index)=>{
        //从displayedTableData的响应式对象数组中的特定json元素中读出里面的id值，并发送给后端
        let TeacherID=displayedTableData.value[index].id
        console.log("id类型是:",typeof TeacherID)
        const token=localStorage.getItem("token")
        if(token==null){
          alert("请先登录")
          router.push("/login")
        }
        checkTeacher(TeacherID).then(res => {
            console.log("===获取老师信息如下：===")
            console.log("res.data是:",res.data)
            console.log("res.data.data是:",res.data.data)
            //将res.data赋值给teacherForm
            teacherForm.id=res.data.id
            teacherForm.name=res.data.data.name
            teacherForm.phone=res.data.data.phone
            teacherForm.birthday=res.data.data.birthday
            teacherForm.sex=res.data.data.sex
            teacherForm.introduce=res.data.data.introduce
            teacherForm.note=res.data.data.note
            teacherForm.roleEmail=res.data.data.roleEmail
            teacherForm.teacherVoList=res.data.data.teacherVoList
        }).catch(err => {
            // error
            console.log(err)
          })
        //数据类型是一个数组，里面有两个json文件
    }


    //处理当前页码变化
    const handleCurrentChange = (val) => {
        currentPage.value = val;
        displayCurrentPageData();
    }
    //刷新当前页数据
    const displayCurrentPageData = () => {
      // const token=localStorage.getItem("token")
      //   axios.post("/api/system-settings/Teacher-management/getOnePageDate",
      //     {page:currentPage.value},
      //     {headers: {Authorization: `${token}`}}
      //     ).then(res => {
      //       displayedTableData.value = res.data.data
      //       startlocation=(currentPage.value-1)*10+1
      //       endlocation=startlocation+displayedTableData.value.length-1
      //     }).catch(error=>{
      //         //输出报错信息
      //         console.log("Error information:", error);
      //         if (error.response.status === 401) {
      //           alert('登录已过期，请重新登录');
      //           //删除token
      //           localStorage.removeItem("token")
      //           router.push("/login")
      //         }
      //         else{alert("未知错误")}
      //     })


      // console.log(localStorage.getItem("token"))
      getOnePageDate(currentPage.value).then(res=>{
        displayedTableData.value = res.data.data
            startlocation=(currentPage.value-1)*10+1
            endlocation=startlocation+displayedTableData.value.length-1
      }).catch(err => {
      // error
      console.log(err)



      })
      
    }
    //删除数据
    const deleteRow = (index) => {
      let TeacherID=displayedTableData.value[index].id
        const token=localStorage.getItem("token")
        //向后端发送axios请求，删除对应id的记录，并重新刷新页面
        deleteTeacher(TeacherID).then(res => {
            console.log("===删除数据库数据===")
            displayedTableData.value = res.data.data
            displayCurrentPageData(); // 显示第一页的数据
        }).catch(err => {
            // error
            console.log(err)
          })
    }

    //tableRowClassName
    const tableRowClassName = ({ row, rowIndex }) => {
        if (rowIndex === 0) {
            return 'warning-row';
        } else if (rowIndex === 1) {
            return 'success-row';
        }
        return '';
    }

    


    //2.通过axios获取后台数据
    onMounted(() => {

      // //加载token
      // const token=localStorage.getItem("token")
      // if(token==null){
      //   alert("请先登录")
      //   router.push("/login")
      // }else{
      //     axios.get("/api/system-settings/Teacher-management/getlength",
      //     {headers: {Authorization: `${token}`}}
      //     ).then(res => {
      //     // console.log("===此为输出数据库总数据长度===")
      //     console.log("这个是从后台调来的数据长度",res.data.data)
      //     total.value = res.data.data // 更新 total 的值
      //     displayCurrentPageData(); // 显示第一页的数据
      //     }).catch(error=>{
      //         //输出报错信息
      //         console.log("Error information:", error);
      //         if (error.response.status === 401) {
      //           alert('登录已过期，请重新登录');
      //           //删除token
      //           localStorage.removeItem("token")
      //           router.push("/login")
      //         }
      //         else{alert("未知错误")}
      //     })

      // }
      // console.log("这里应当输出token的值",localStorage.getItem("token"))
      
      
      getlength().then(res=>{
            // console.log("这个是从后台调来的数据长度",res.data.data)
            total.value = res.data.data // 更新 total 的值
            displayCurrentPageData(); // 显示第一页的数据
          }
        ).catch(err => {
        // error
        console.log(err)
      })

    })
  
</script>

<style scoped>
/*表格样式*/ 
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
/*表格样式##*/ 

/*分页样式*/ 
.example-pagination-block {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
}
/*分页样式##*/ 

/*tab组件标签样式*/
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
} 
/*tab组件标签样式#*/
</style>